package com.stylefeng.guns.biz.acct;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.common.bo.ImageFileBo;
import com.stylefeng.guns.common.bo.WebuserBo;
import com.stylefeng.guns.common.constant.cache.DictKey;
import com.stylefeng.guns.common.constant.enums.IntegralTransType;
import com.stylefeng.guns.common.constant.enums.IsAdd;
import com.stylefeng.guns.common.dto.acct.AcctRegisterReq;
import com.stylefeng.guns.common.dto.acct.AddUserBaseInfoReq;
import com.stylefeng.guns.common.dto.acct.AvatarReq;
import com.stylefeng.guns.common.dto.acct.AvatarResp;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.persistence.dao.DictMapper;
import com.stylefeng.guns.common.persistence.dao.SysUserMapper;
import com.stylefeng.guns.common.persistence.dao.WebuserMapper;
import com.stylefeng.guns.common.persistence.model.Dict;
import com.stylefeng.guns.common.persistence.model.Webuser;
import com.stylefeng.guns.common.util.Bese64ToImageUtil;
import com.stylefeng.guns.common.util.InviteUtil;
import com.stylefeng.guns.common.util.WebUserKit;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.util.IdGenerator;
import com.stylefeng.guns.modular.system.service.IWebuserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author carloszhang
 */
@Slf4j
@Component("webUserOptBizImpl")
public class WebUserOptBizImpl {

    @Autowired
    private IWebuserService iWebuserService;

    @Value("${spring.self-upload-file-path}")
    private String uploadFilePath;

    private String AVATER_PATH = "avatar/";//项目一头像

    @Autowired
    private WebuserMapper webuserMapper;

    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private LoginBizImpl loginBizImpl;

    /**
     * 修改机构信息
     */
    public boolean modifyUserBaseInfo(AddUserBaseInfoReq req) {

        WebuserBo webuserBo = WebUserKit.getWebuserBo();
        Webuser existWebUser = iWebuserService.qryExistWebUserByTelno(webuserBo.getTelno());

        boolean result = Boolean.TRUE;
        String fileName = StringUtils.EMPTY;
        if (StringUtils.isNotBlank(req.getAvatarBase64())) {
            ImageFileBo imageFileBo = Bese64ToImageUtil.base64ToImageFileBo(req.getAvatarBase64());
            fileName = IdGenerator.getId().concat(imageFileBo.getImageSuffix());
            String filePath = new StringBuilder()
                    .append(uploadFilePath)
                    .append(AVATER_PATH)
                    .append(fileName)
                    .toString();
            result = Bese64ToImageUtil.base64ToImageOutput(imageFileBo.getImageData(), filePath);
        }
        if (result) {
            boolean updateFlag = Boolean.FALSE;
            Webuser tmp = new Webuser();
            tmp.setId(existWebUser.getId());
            if (StringUtils.isNotBlank(fileName)) {
                tmp.setAvatar(fileName);
                updateFlag = Boolean.TRUE;
            }
            if (StringUtils.isNotBlank(req.getNickName())) {
                tmp.setNickname(req.getNickName());
                updateFlag = Boolean.TRUE;
            }
            if (req.getProvince() != null && req.getCity() != null) {
                tmp.setProvince(req.getProvince());
                tmp.setCity(req.getCity());
                updateFlag = Boolean.TRUE;
            }
            if (updateFlag) {
                Integer integer = webuserMapper.updateByPrimaryKeySelective(tmp);
                return BooleanUtils.toBoolean(integer);//更新是否成功
            }

        }
        return false;

    }

    /**
     * 更新头像信息
     */
    public AvatarResp uploadAvatarInfo(AvatarReq req) {
        AvatarResp resp = new AvatarResp();
        if (StringUtils.isNotBlank(req.getAvatarBase64()) && (req.getSystemName().equals("yjly") || req.getSystemName().equals("yjcf"))) {
            ImageFileBo imageFileBo = Bese64ToImageUtil.base64ToImageFileBo(req.getAvatarBase64());
            String fileName = IdGenerator.getId().concat(imageFileBo.getImageSuffix());
            String filePath = new StringBuilder()
                    .append(uploadFilePath)
                    .append(req.getSystemName())
                    .append("/")
                    .append(fileName)
                    .toString();
            Boolean result = Bese64ToImageUtil.base64ToImageOutput(imageFileBo.getImageData(), filePath);
            if (result) {
                resp.setAvatarPath(fileName);
                return resp;
            } else {
                throw new GunsException(BizExceptionEnum.UPLOAD_IMAGE_ERROR);
            }
        } else {
            throw new GunsException(BizExceptionEnum.UPLOAD_IMAGE_ERROR);
        }
    }

    public boolean verifyPayCipher(String payCipher) {
        WebuserBo webuserBo = WebUserKit.getWebuserBo();
        Webuser existWebUser = iWebuserService.qryExistWebUserByTelno(webuserBo.getTelno());
        return iWebuserService.validPayCipher(existWebUser, payCipher);
    }


    private static final Integer inviteDict = 25;//邀请注册

    @Transactional(rollbackFor = Exception.class)
    public boolean registerUser(AcctRegisterReq req) {
        return false;
    }

    public static void main(String[] args) {
        System.out.println(InviteUtil.createInviteCode(1000007));
    }
}
